package dataStructure;

/**
 *用数组实现栈
 */
public class StackTest {

    int[] date;
    private int size;
    private int top;

    public StackTest(int size) {
        this.size = size;
        date = new int[size];
        top = -1;
    }

    public int getSize() {
        return size;
    }

    public int getTop() {
        return top;
    }

    public boolean isEmpty() {
        return top == -1;
    }

    public boolean isFull() {
        return (top + 1) == size;
    }

    /**
     * 压栈操作
     *
     * @param data
     * @return
     */
    public boolean push(int data) {
        if (isFull()) {
            System.out.println("栈满了");
            return false;
        } else {
            top++;
            this.date[top] = data;
            return true;
        }
    }

    /**
     * 获取栈顶元素
     *
     * @return
     * @throws Exception
     */
    public int pop() throws Exception {
        if (isEmpty()) {
            throw new Exception("栈空");
        } else {
            return this.date[top--];
        }
    }

    /**
     * 获取栈顶元素，但是不弹出
     *
     * @return
     */
    public int peek() {
        return this.date[getTop()];
    }

    public static void main(String[] args) {
        StackTest stack = new StackTest(20);
        stack.push(1);
        stack.push(6);
        stack.push(2);
        stack.push(4);
        System.out.println("目前的栈顶元素为：" + stack.peek());

        System.out.println("目前的栈容量为:"+stack.getSize());
        while (!stack.isEmpty()) {
            try {
                System.out.println(stack.pop());
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
    }

}
